package service

import (
	"fmt"

	"gitee.com/gomaster/book-library/entity"
	"gitee.com/gomaster/book-library/repo"

	"github.com/gin-gonic/gin"
)

// InitOrderHandler 初始化订单
func InitOrderHandler(r *gin.Engine) {
	og := r.Group("/order")
	og.POST("/lend", BookLend)
	og.POST("/back", BookBack)
	og.POST("/renew", BookRenew)
	og.POST("/getBorrow", GetUserBorrow)
}

// BookLend 图书借阅
func BookLend(c *gin.Context) {
	bkLend := &entity.BorrowRecord{}
	err := c.BindJSON(bkLend)
	if err != nil {
		fmt.Printf("param invalid")
		entity.ReturnFail(c, "param invalid")
		return
	}

	handler := repo.GetRepoHandler()
	bookInfo := handler.BookGet(bkLend.IBSN)
	if bookInfo == nil {
		fmt.Printf("当前图书不存在, ibsn:%s", bkLend.IBSN)
		entity.ReturnFail(c, "book does not exists")
		return
	}

	err = handler.BorrowAdd(bkLend.IBSN, bkLend.Name)
	if err != nil {
		fmt.Printf("借阅图书失败, err:%s", err.Error())
		entity.ReturnFail(c, "borrow failed, msg:"+err.Error())
		return
	}
	entity.ReturnOK(c, nil)
}

// BookBack 图书归还
func BookBack(c *gin.Context) {
	lendInfo := &entity.BorrowRecord{}
	err := c.ShouldBind(lendInfo)
	if err != nil {
		fmt.Printf("parse request failed, err:%s", err.Error())
		entity.ReturnFail(c, err.Error())
		return
	}

	err = repo.GetRepoHandler().BorrowBack(lendInfo.IBSN, lendInfo.Name)
	if err != nil {
		fmt.Printf("还书失败, err:%s", err.Error())
		entity.ReturnFail(c, err.Error())
		return
	}
	entity.ReturnOK(c, nil)
}

func GetUserBorrow(c *gin.Context) {
	record := &entity.BorrowRecord{}
	err := c.BindJSON(record)
	if err != nil {
		fmt.Printf("parse request param failed, err:%s", err.Error())
		entity.ReturnFail(c, err.Error())
		return
	}

	handler := repo.GetRepoHandler()
	books := handler.BorrowListByName(record.Name)
	entity.ReturnOK(c, books)
}

// BookRenew 图书续借
func BookRenew(c *gin.Context) {
	entity.ReturnOK(c, "todo")
}
